# -*- coding: utf-8 -*-
"""
Created on Sun Feb 05 10:46:24 2012

@author: han
"""
import sys, stat
import math
import subprocess as subp
## {{{ http://code.activestate.com/recipes/52224/ (r1)
from os.path import exists, join
import os.path
from os import pathsep
import string
import os
import datetime
import time
import socket
#sys.path.append('..\\fits\\')
from astropysics.coords import match_coords
from template_extract_func import template_extract_func


t0 = datetime.datetime.now()

def search_file(filename, search_path):
   """Given a search path, find file
   """
   file_found = 0
   paths = string.split(search_path, pathsep)
   for path in paths:
      if exists(join(path, filename)):
          file_found = 1
          break
   if file_found:
      return os.path.abspath(join(path, filename))
   else:
      return None

def column(matrix, i):
    return [row[i] for row in matrix]

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def recvfile(filename):
    print "server ready, now client recv file~~"
    f = open(filename, 'wb')
    while True:
        data = s.recv(4096)
        if data == 'EOF':
            print "recv file success!"
            break
        f.write(data)
    f.close()

def confirm(s, client_command):
    s.send(client_command)
    data = s.recv(4096)
    if data == 'ready':
        return True

    
if __name__ == '__main__':
#    print sys.argv
    zs=0
if not sys.argv[1:]:
    sys.argv += ["E:/tmp_pool", "223.13", "10.50", "2.5", "0","14.3"]
uppath = sys.argv[1]
ra=sys.argv[2]
dec=sys.argv[3]
radius_str = sys.argv[4]
radius=float(radius_str)
rmag_lower_str = sys.argv[5]
rmag_lower=float(rmag_lower_str)
rmag_upper_str = sys.argv[6]
rmag_upper=float(rmag_upper_str)
if uppath[-1] != '/' or  uppath[-1] != '\\':
    uppath = uppath + '/'
print uppath
if ra.count(':') > 0 and dec.count(':') > 0 :
    rahms = ra
    decdms = dec
    radeg = float(rahms.split(":")[0])/24.0*360.0+float(rahms.split(":")[1])/60.0*15.0+float(rahms.split(":")[2])/3600.0*15.0
    decdeg = float(decdms.split(":")[0])+float(decdms.split(":")[1])/60.0+float(decdms.split(":")[2])/3600.0
    print rahms, decdms, radeg, decdeg
else:
    radeg = float(ra) 
    decdeg = float(dec)
    ra_h = int(radeg/15.0)
    ra_m = int((radeg/15.0 - ra_h)*60.0)
    ra_s = (((radeg/15.0 - ra_h)*60.0) - ra_m)*60.0
    rahms = "%02d:%02d:%0.1f" % (ra_h,ra_m,ra_s)
    dec_d = int(decdeg)
    if dec_d >= 0:
        dec_m = int((decdeg - dec_d)*60.0)
        dec_s = (((decdeg - dec_d)*60.0) - dec_m)*60.0
        decdms = "%02d:%02d:%0.1f" % (dec_d,dec_m,dec_s)
    else:
        dec_m = abs(int((decdeg - dec_d)*60.0))
        dec_s = (abs((decdeg - dec_d)*60.0) - dec_m)*60.0
        decdms = "%02d:%02d:%0.1f" % (dec_d,dec_m,dec_s)
    print rahms, decdms, radeg, decdeg

homedir = os.getcwd()
sky_area_mosaic_file = homedir+'/sky_area_mosaic_minigwac.dat'
sky_area_mosaic_file_dev = open(sky_area_mosaic_file,'rU')

lines_mosaic=sky_area_mosaic_file_dev.read().splitlines()
sky_area_mosaic_file_dev.close()

area_cen_ra = [0 for x in range(len(lines_mosaic)*2)]
area_cen_dec = [0 for x in range(len(lines_mosaic)*2)]
m = 0
temp_avaliable = 0
for line1 in lines_mosaic:
    coor_array=line1.split()[0]
    for n in range(2):
        area_cen_dec[m] = float(coor_array[-2:]) + (n * 20) - 10
        area_cen_ra[m] = (float(coor_array) - float(coor_array[-2:]) )/100
        dis = math.sqrt((radeg - area_cen_ra[m])**2 + (decdeg - area_cen_dec[m])**2)
        if dis <= 1.5:
            temp_cen_ra = area_cen_ra[m]
            temp_cen_dec = area_cen_dec[m]
            temp_avaliable = 1
        m = m + 1
#print area_cen_ra,area_cen_dec,m
#if temp_avaliable == 1 :
#    print temp_cen_ra,temp_cen_dec,temp_avaliable
#    
#    homedir = os.getcwd()
#    configuration_file = homedir+'/configuration.dat'
#    configuration_file_dev = open(configuration_file,'rU')
#    
#    lines1=configuration_file_dev.read().splitlines()
#    configuration_file_dev.close()
#    
#    for line1 in lines1:
#        word=line1.split()
#    #    print word
#        if word[0] == 'user':
#            user = word[2]
#        elif word[0] == 'ip':
#            ip = word[2]
#        elif word[0] == 'mypassword':
#            mypassword = word[2]
#        elif word[0] == 'socket_port':
#            socket_port = int(word[2])
#    temp_cen_ra_str = "%0.1f" % (temp_cen_ra)
#    temp_cen_dec_str = "%0.1f" % (temp_cen_dec)
#    temp_file = "temp_" + temp_cen_ra_str + "_" + temp_cen_dec_str + "_rad13.5_magr14.0.txt"
#    client_command = 'get ' +  temp_file + ' ' + uppath                         
#    try:
#        s.connect((ip,socket_port))
#        while 1:               
#            if len(client_command.split()) == 2:                  
#                action, temp_file = client_command.split()
#            if len(client_command.split()) == 3:
#                action, temp_file,path = client_command.split()
#            if action == 'get':
#                if confirm(s, client_command):
#                    filename_new = path+temp_file              
#                    recvfile(filename_new)
#                    break
#                else:
#                    print "server get error!"
#            else:
#                print "command error!"
#    except socket.error,e:
#        print "get error as",e
#    finally:
#        s.close()

#else:
#    print 'No template avaliable, Now makeing one'
catalogextract_result = template_extract_func(radeg,decdeg,radius,rmag_lower,rmag_upper)
catalogextract_result = [list(row) for row in catalogextract_result]
uppath_slash = uppath.replace('\\','/')
uppath_slash = uppath_slash + '/'
#outputfile_name = "testall.txt"
ra_str = "%0.1f" % (float(ra))
dec_str = "%0.1f" % (float(dec))
outputfile_name = "temp_" + ra_str + "_" + dec_str + "_rad" + radius_str + "_magr" + rmag_upper_str + ".txt"
outputfile_name_slash = uppath_slash+outputfile_name
outputfile_backslash = uppath+outputfile_name
outputfile=outputfile_name_slash
#print outputfile
g = open(outputfile,'w')
#print RAdeg
#, DEdeg,  Bmag, Vmag, Rmag, Rsource
for m in catalogextract_result:
#    print m[0],m[1],m[3],m[3],m[7],m[7]
    g.write("%s %s %s %s %s %s\n" % (m[0],m[1],m[3],m[3],m[7],m[7]))
g.close()
        
num_stars = (len(catalogextract_result))    
print 'Match Found: ',num_stars
delta_t = datetime.datetime.now() - t0
print 'Time Spent: ',delta_t
